function createSold(stock_row){
  $.ajax({
        url: "/sold/create",
        type: "POST",
        data: {sold: {
                 ref_id:$("#bill_ref_id").attr("value") , 
                 stock_id: stock_row.attr('stock_id'),
                 cost: stock_row.find('.cost').text() 
        }},
        success: function(data){addSoldRow(data);}
  });
}

function updateSold(soldRow){
  $.ajax({
        url: "/sold/update",
        type: "POST",
        data: {sold: {
                 id: soldRow.attr('sold_id'),
                 cost: soldRow.find('.cost').val(),
                 quantity: soldRow.find('.itemQuantity').val() 
        }},
        success: function(){updateTotal(soldRow);},
        error: function(originalData,status){
          var data = jQuery.parseJSON(originalData.responseText)
                soldRow.find(".cost").val(data.cost);
              soldRow.find(".itemQuantity").val(data.quantity);
        }
  });
}

function addSoldRow(data){
  var $clone = $("#template").clone();
  $clone.attr('sold_id',data.sold.id);
  $clone.removeAttr('id');
  $clone.removeAttr('style');
  $clone.find(".name").text(data.stock.name);
  $clone.find(".company").text(data.stock.company);
  $clone.find(".cost").val(data.sold.cost);
  $clone.find(".itemQuantity").val(data.sold.quantity);
  $("#template").after($clone);
  $clone.show();
  updateTotal();
}

